// Copyright 2023 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef _SOCKET_SERVER_H_
#define _SOCKET_SERVER_H_

#include <string>
#include <vector>
#include <iostream>
#include <memory>
#include "signal.h"

#include "SocketBase.h"

namespace master {

static const uint32_t SOCKET_HEAD_FLAG = 0x5A5A5A5A;
static const uint32_t SOCKET_HEAD_FLAG_LENGTH = 4;
static const uint32_t SOCKET_CMD_LENGTH = 2;
static const uint32_t SOCKET_DATA_BUF_LENGTH = 4;
static const uint32_t SOCKET_HEAD_LENGTH = 10;

typedef struct SocketInfoS {
    int fdSock;
    uint32_t port;
    std::string ipAddr;
    bool firstRun;
    std::shared_ptr<uint8_t> recvBuf;
    uint32_t recvBufLen;
    int recvBufOffset;

    std::shared_ptr<uint8_t> sendBuf;
    uint32_t sendBufLen;
} SocketInfoT;

class SocketServer : public BaseSocket {
public:
    SocketServer();

    ~SocketServer();

    int acceptNewConnect(int *fd);

    std::shared_ptr<SocketInfoT> findSocketInfoIt(int connFd);

    int eraseSocketInfoIt(int connFd);

    std::shared_ptr<SocketInfoT> createSocketInfoIt(int connFd);

    int socketServerReadData(std::shared_ptr<SocketInfoT> pSocketInfo);

    int socketServerWriteData(int connFd, std::shared_ptr<SocketInfoT> pSocketInfo);

    int socketServerInit(uint16_t ipPort);

private:
    std::mutex mutexMap;
};
};
#endif